import { buyAuth, queryMyBoughtAuth, queryMySoldAuth } from '@/api/auth';

const song = {
  state: {
    myBoughtAuths: [],
    mySoldAuths: [],
  },
  mutations: {
    UPDATE_BOUGHT_AUTHS: (state, payload) => {
      state.myBoughtAuths = payload;
    },
    UPDATE_SOLD_AUTHS: (state, payload) => {
      state.mySoldAuths = payload;
    },
  },
  actions: {
    buySongAuth(_, payload) {
      return new Promise((resolve, reject) => {
        buyAuth(payload)
          .then((res) => {
            const { meta } = res;
            if (meta.success && meta.code === 6666) {
              resolve(meta);
            } else {
              reject(meta);
            }
          });
      });
    },
    getMyBoughtAuths({ commit }, uid) {
      return new Promise((resolve, reject) => {
        queryMyBoughtAuth(uid).then((res) => {
          const { meta, data } = res;
          if (meta.success && meta.code === 6666) {
            commit('UPDATE_BOUGHT_AUTHS', data.songs);
            resolve(meta);
          } else {
            reject(meta);
          }
        });
      });
    },
    getMySoldAuths({ commit }, uid) {
      return new Promise((resolve, reject) => {
        queryMySoldAuth(uid).then((res) => {
          const { meta, data } = res;
          if (meta.success && meta.code === 6666) {
            commit('UPDATE_SINGERS', data.singers);
            resolve();
          } else {
            reject(meta);
          }
        });
      });
    },
  },
  getters: {
    myBoughtAuths: state => state.myBoughtAuths,
    mySoldAuths: state => state.mySoldAuths,
  },
};

export default song;
